package cn.kgc.service.impl;


import cn.kgc.dto.DishDto;
import cn.kgc.entity.Dish;
import cn.kgc.entity.DishFlavor;
import cn.kgc.mapper.DishMapper;
import cn.kgc.service.DishFlavorService;
import cn.kgc.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service

public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品表，同时保存对应的的口味数据
     */
    @Override
    @Transactional         //提供事务支持
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品信息
        this.save(dishDto);
        //获取菜品信息ID
        Long dishid = dishDto.getId();

        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();

        //通过stream 遍历 赋值给口味表
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishid);  // 遍历给 口味表的 ID
            return item;
        }).collect(Collectors.toList());  //整合 转成list集合

//保存菜品口味到 dish fishvorservice
        dishFlavorService.saveBatch(flavors);  //添加集合 saveBatch
    }

    @Override
    public DishDto getByWithFlavor(Long id) {
        //查询菜品基本信息 ，从Dish 表查询
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        //把 dish 里的属性 拷贝到 dishDto
        BeanUtils.copyProperties(dish, dishDto);
        //查询当前菜品对应的口味信息，从dishFlavor表中查
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        // 更新 dish 表基本信息
        this.updateById(dishDto);
        //清理当前菜品对应口味数据 -- dish_flavor 表的delete操作
        //  sql： delete from dish_flavor where dish_id = ???
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);
   // 添加当前提交过来的口味数据 -- dish flavor 表的 添加操作
        List<DishFlavor> flavors = dishDto.getFlavors();

        //通过stream 遍历 赋值给口味表
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());  // 遍历给 口味表的 ID
            return item;
        }).collect(Collectors.toList());  //整合 转成list集合

        dishFlavorService.saveBatch(flavors);

    }

}
